package com.ww.util.phone;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Paths;

public class PhoneData {
    private DataInputStream inputStream;
    private int version;
    private int firstPhoneRecordOffset;
    private int phoneRecordCount;

    public PhoneData(String datFilePath) throws IOException {
        File file = new File(datFilePath);
        if (!file.exists()) {
            throw new IOException("File does not exist: " + datFilePath);
        }

        try (FileInputStream fis = new FileInputStream(file);
             DataInputStream dis = new DataInputStream(fis)) {
            this.inputStream = dis;

            // Read the header information
            this.version = dis.readInt();
            this.firstPhoneRecordOffset = dis.readInt();

            // Calculate the number of phone records
            long length = file.length();
            this.phoneRecordCount = (int) ((length - firstPhoneRecordOffset) / (4 * 3)); // Assuming each record is 4 bytes * 3
        }
    }

    // Getter methods for the class variables
    public int getVersion() {
        return version;
    }

    public int getFirstPhoneRecordOffset() {
        return firstPhoneRecordOffset;
    }

    public int getPhoneRecordCount() {
        return phoneRecordCount;
    }

    // Method to read phone records, if needed
    public void readPhoneRecords() throws IOException {
        if (inputStream != null) {
            inputStream.skipBytes(firstPhoneRecordOffset); // Skip to the first phone record
            for (int i = 0; i < phoneRecordCount; i++) {
                int phoneNumber = inputStream.readInt();
                byte carrierCode = inputStream.readByte();
                // Process the phone number and carrier code as needed
            }
        } else {
            throw new IOException("Input stream is not initialized.");
        }
    }

    public static void main(String[] args) {
        String datFilePath = Paths.get("D:/test/phone.dat").toString(); // Path to the data file
        try {
            PhoneData phoneData = new PhoneData(datFilePath);
            System.out.println("Version: " + phoneData.getVersion());
            System.out.println("First Phone Record Offset: " + phoneData.getFirstPhoneRecordOffset());
            System.out.println("Phone Record Count: " + phoneData.getPhoneRecordCount());

            // Optionally, read the phone records
            phoneData.readPhoneRecords();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
